package com.platform.sms.tencent.service;

import com.github.qcloudsms.*;
import com.github.qcloudsms.SmsMultiSenderResult.Detail;
import com.platform.base.common.dto.Result;
import com.platform.base.utils.Log;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service(ITencentSmsService.ID)
public class TencentSmsServicempl implements ITencentSmsService {

	@Value("${config.sms.tencent.appId}")
	private int appId;
	
	@Value("${config.sms.tencent.appKey}")
	private String appKey;
	
	@Override
	public Result sendCodeByMessage(int templateId, String mobie, ArrayList<String> params) {
		Log.i("sendCodeByMessage接口参数==>templId: {}, 手机号码：{}， 其它参数：{}", templateId, mobie, params.toString());
		Result rs = new Result();
		try {
			SmsSingleSender sender = new SmsSingleSender(appId, appKey);
			SmsSingleSenderResult result = sender.sendWithParam("86", mobie, templateId, params, "", "", "");
			//发送成功
			rs.setSuccess(result.result == 0 ? true : false);
			rs.setMessage(result.errMsg);
			rs.setAttribute("ext", result.ext);
			rs.setAttribute("fee", result.fee);
			rs.setAttribute("sid", result.sid);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
		return rs;
	}

	@Override
	public Result sendCodeByVoice(String mobie, String code) {
		Log.i("sendCodeByVoice接口参数==>手机号码：{}， 验证码：{}", mobie, code);
		Result rs = new Result();
		try {
			SmsVoiceVerifyCodeSender smsVoiceVerifyCodeSender = new SmsVoiceVerifyCodeSender(appId, appKey);
			SmsVoiceVerifyCodeSenderResult result = smsVoiceVerifyCodeSender.send("86", mobie, code, 2, "");
			//发送成功
			rs.setSuccess(result.result == 0 ? true : false);
			rs.setMessage(result.errMsg);
			rs.setAttribute("ext", result.ext);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
		return rs;
	}

	@Override
	public Result groupSend(int templateId, String sign, ArrayList<String> phoneNumbers, ArrayList<String> params) {
		Log.i("groupSend接口参数==>templId: {}, sign: {}, 手机号码：{}， 其它参数：{}", templateId, sign, phoneNumbers.toString(), params.toString());
		// 如果有超过5000条短信请重新封装
		if(phoneNumbers.size() > 5000){
			throw new RuntimeException("发送短信总数量不能超过5000条");
		}
		if(phoneNumbers.size() == 0){
			throw new RuntimeException("发送短信总数量不能为0条");
		}
		Result rs = new Result();
		try{
			Log.i("API短信群发正在处理中...");
	        SmsMultiSender multiSender = new SmsMultiSender(appId, appKey);
	        ArrayList<Detail> errorDetail = new ArrayList<Detail>();
	        ArrayList<String> successDetail = new ArrayList<String>();
	        
	        int perCount = 20,index = 0;
			int times = phoneNumbers.size() / perCount;
			do  {
				List<String> listTemp = null;
				Log.i("API短信群发分段处理中...");
				if(phoneNumbers.size() > 0){
					if(phoneNumbers.size() >= perCount){
						listTemp = phoneNumbers.subList(0, perCount);// listTemp是分段处理逻辑的参数
					}else{
						listTemp = phoneNumbers.subList(0, phoneNumbers.size());// listTemp是分段处理逻辑的参数
					}
				}
				//遍历当前的值是否正确
				if(listTemp != null){
					Log.i("API短信群发分段手机号构建中...");
					 // 初始化群发
			        ArrayList<String> smsGroup = new ArrayList<String>();
			        for(String temp: listTemp){
			        	// 手机号码校验
			        	if(temp.length() == 11){
			        		smsGroup.add(temp);
			        	}
			        }
			        if(smsGroup.size() != 0){
						Log.i("API短信群发正在发送中...");
						SmsMultiSenderResult multiSenderResult = multiSender.sendWithParam("86", smsGroup, templateId, params, sign, "", "");
						Log.i("API短信群发发送结束...");
	                	int result = multiSenderResult.result;
	                	if(result == 0){
	                		ArrayList<Detail> detailsList = multiSenderResult.details;
	                		for(Detail dl: detailsList){
	                			if(dl.result != 0){
	                				errorDetail.add(dl);
	                			}else{
	                				successDetail.add(dl.mobile);
	                			}
	                		}
	                	}else{
							String msg = multiSenderResult.errMsg;
							Log.e("短信发送失败Msg: {}", msg);
							rs.setSuccess(false);
							rs.setMessage(msg);
	                		return rs;
	                	}
						phoneNumbers.removeAll(listTemp);
			        }
				}
				index++;
			}
			while (index<=times);
			Log.i("API短信群发处理结束...");
			rs.setSuccess(true);
			rs.setMessage("批量短信发送成功");
			rs.setAttribute("successPhones", successDetail);
			rs.setAttribute("errorDetail", errorDetail);
	        return rs;
		}catch(Exception e){
			e.printStackTrace();
			rs.setSuccess(false);
			rs.setMessage(e.getMessage());
			return rs;
		}
	}
	
}
